package org.example.view.admin;

import org.example.controller.UserController;
import org.example.data.User;
import org.example.data.UserMessage;
import org.example.data.UserWithDetails;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

public class UserManagement extends JFrame {
    private final UserController userController = new UserController();
    private JTable userTable;
    private DefaultTableModel tableModel;

    public UserManagement() {
        setTitle("用户管理界面");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        initializeComponents();
        populateUserData();
    }

    private void initializeComponents() {
        JPanel mainPanel = new JPanel(new BorderLayout());

        // 表格初始化
        String[] columnNames = {"用户id","用户名", "姓名", "电话号码", "性别", "年龄", "用户类型", "操作"};
        tableModel = new DefaultTableModel(columnNames, 0);
        userTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(userTable);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 操作列渲染
        userTable.getColumnModel().getColumn(7).setCellRenderer(new ButtonRenderer());
        userTable.getColumnModel().getColumn(7).setCellEditor(new ButtonEditor(new JCheckBox()));
        JButton exit = new JButton("退出");
        exit.addActionListener(e->{
            dispose(); // 关闭当前界面
        });
        mainPanel.add(exit,BorderLayout.SOUTH);
        add(mainPanel);
        setVisible(true);
    }

    private void populateUserData() {
        try {
            List<UserWithDetails> userList = userController.listUsers().getData();
            if (userList != null) {
                for (UserWithDetails user : userList) {
                    Object[] rowData = {
                            user.getUser().getId(),
                            user.getUser().getUsername(),
                            user.getUserMessage().getName(),
                            user.getUserMessage().getPhoneNumber(),
                            user.getUserMessage().getSex(),
                            user.getUserMessage().getAge(),
                            user.getUser().getUsertype(), ""}; // 操作列留空，由ButtonRenderer和ButtonEditor填充
                        tableModel.addRow(rowData);
                }
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载用户数据时发生错误：" + e.getMessage());
        }
    }

    // 自定义渲染器和编辑器
    private class ButtonRenderer extends JButton implements TableCellRenderer {
        public ButtonRenderer() {
            setOpaque(true);
        }

        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus, int row, int column) {
            setText((value == null) ? "" : value.toString());
            return this;
        }
    }

    private class ButtonEditor extends DefaultCellEditor {
        protected JButton button;

        public ButtonEditor(JCheckBox checkBox) {
            super(checkBox);
            button = new JButton();
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    int modelRow = userTable.convertRowIndexToModel(userTable.getEditingRow());
                    String userType = (String) tableModel.getValueAt(modelRow, 6);
                    switchUserType(modelRow, userType);
                }
            });
        }

        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row, int column) {
            if ("管理员".equals(value)) {
                button.setText("降级为普通用户");
            } else {
                button.setText("升级为管理员");
            }
            return button;
        }
    }

    // 处理用户类型切换逻辑
    private void switchUserType(int modelRow, String userType) {
        // 这里应该调用UserController中相应的方法来处理用户类型的更改
        // 示例逻辑，实际根据需求调整
        try {
            int userId = (int) tableModel.getValueAt(modelRow, 0);
            if ("管理员".equals(userType)) {
                userController.updateUserRole(userId, "普通用户");
            } else {
                userController.updateUserRole(userId, "管理员"); // 同上
            }
            tableModel.setValueAt(userType.equals("管理员") ? "普通用户" : "管理员", modelRow, 6); // 更新表格显示
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "更新用户类型失败：" + e.getMessage());
        }
    }
}